package server;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import network.Buddy;
import network.Status;

public class UserCollection implements Serializable, Iterable<User> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1810450087660942826L;

	
	private HashMap<String,User> users;
	
	public UserCollection() {
		users=new HashMap<String, User>();
	}
	
	public void addUser(User user) {
		users.put(user.getUserName(), user);
	}

	public boolean containsUser(String name){
		return users.containsKey(name);
	}

	public User getUser(String name){
		return (User) users.get(name);
	}

	public boolean isUserOnline(User o){
		return (users.get(o).getStatus() == Status.ONLINE);
	}

	public void removeUser(String userName) {
		users.remove(userName);
	}

	public void setAllStatus(Status s){
		Collection <User> aux = users.values();
		users=new HashMap<String, User>();
		
		for(User us : aux){
			us.setStatus(s);
			us.setAllBuddiesStatus(s);
			users.put(us.getUserName(), us);
		}
	}

	public void setState(User u, Status s){
		Collection <User> aux = users.values();
		users=new HashMap<String, User>();
		
		for(User us : aux){
			if(us.equals(u)){
				us.setStatus(s);
			}else{
				us.updateBuddy(new Buddy(u.getUserName(),s));
			}
			users.put(us.getUserName(), us);
		}
	}
	
	public String toString(){
		String s = "{";
		for(User us : this){
			s = s.concat(us.toString() + ",");
		}
		s = s.substring(0, s.length()-1).concat("}");
		return s;	
	}

	public void updateUser(User user){
		this.removeUser(user.getUserName());
		this.addUser(user);
	}

	@Override
	public Iterator<User> iterator() {
		return users.values().iterator();
	}
	
}
